package leetcode.D300.T239;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: 18362
 * @Create: 2022-02-19 19:53:28 星期六
 */

class Solution {
    // 一刷
    /*public int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> dq = new LinkedList<>();
        for(int i=0; i<k-1; ++i) {
            while(!dq.isEmpty() && nums[dq.getLast()] <= nums[i])
                dq.removeLast();
            dq.addLast(i);
        }
        int i = k-1;
        int[] result = new int[nums.length - k + 1];
        while(i < nums.length) {
            while(!dq.isEmpty() && nums[dq.getLast()] <= nums[i])
                dq.removeLast();
            dq.addLast(i);
            if (dq.getFirst() < (i-k+1))
                dq.removeFirst();
            result[i-k+1] = nums[dq.getFirst()];
            ++i;
        }
        return result;
    }*/

    // 二刷
    public int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> window = new LinkedList<>();
        for (int i=0; i<k-1; ++i) {
            while (!window.isEmpty() && nums[window.getLast()] < nums[i])
                window.removeLast();
            window.addLast(i);
        }
        int[] res = new int[nums.length - k + 1];
        for (int i=k-1; i<nums.length; ++i) {
            if (!window.isEmpty() && window.getFirst() < i-k+1)
                window.removeFirst();
            while (!window.isEmpty() && nums[window.getLast()] < nums[i])
                window.removeLast();
            window.addLast(i);
            res[i-k+1] = nums[window.getFirst()];
        }
        return res;
    }
}
